<template>
  <div>
    <el-card>
      <div class="list-toolbar">
        <el-button color="#1a7bb9" class="btn" @click="handleOpenDialog('新增收入记录')">新增</el-button>
        <el-button color="#1ab394" class="btn" :disabled="editBtnDisabled" @click="handleOpenDialog('修改收入记录')">修改</el-button>
        <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="HandleDelete()">
          <template #reference>
            <el-button color="#ed5565" class="btn" :disabled="delBtnDisabled">删除</el-button>
          </template>
        </el-popconfirm>
        <el-button color="#23c6c8" class="btn" @click="handleImport">导入</el-button>
        <el-button color="#f8ac59" class="btn" @click="handleExport">导出</el-button>
      </div>

      <div class="table">
        <el-table
            :data="tableData"
            header-cell-class-name="table-cell"
            show-overflow-tooltip
            @selection-change="handleSelectionChange"
            class="list-data">
          <el-table-column type="selection" :selectable="selectable" width="55" />
          <el-table-column prop="id" label="ID" width="50" />
          <el-table-column prop="username" label="交易用户" width="125" />
          <el-table-column prop="fundAccountName" label="资金账户" width="125" />
          <el-table-column prop="incomeCategory" label="收入分类" width="125" />
          <el-table-column prop="amount" label="收入金额" width="125" />
          <el-table-column prop="remark" label="备注" width="125" />
          <el-table-column prop="transactionTime" label="交易时间" width="200" />
          <el-table-column prop="createTime" label="创建时间" width="200" />
          <el-table-column prop="updateTime" label="更新时间" width="200" />
          <el-table-column fixed="right" label="Operations" width="150">
            <template #default="{ row }">
              <el-button color="#1ab394" size="small" class="btn" @click="handleOpenDialog('修改收入记录', row)">修改</el-button>
              <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="HandleDelete(row)">
                <template #reference>
                  <el-button color="#ed5565" size="small" class="btn">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="pageSizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
        draggable
        align-center
        v-model="dialogFormVisible"
        :title="dialogTitle"
        width="50%"
        class="custom-dialog">
      <el-form :model="form" class="form-dialog">
        <el-form-item label="ID" v-show="showIdInput" :label-width="formLabelWidth">
          <el-input v-model="form.id" disabled autocomplete="off" />
        </el-form-item>
        <el-form-item label="交易用户" :label-width="formLabelWidth">
          <el-select
              v-model="form.username"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="userRemoteMethod"
              :loading="loading"
          >
            <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.username"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资金账户" :label-width="formLabelWidth">
          <el-select
              v-model="form.fundAccountName"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="fundAccountRemoteMethod"
              :loading="loading"
          >
            <el-option
                v-for="item in fundAccountOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收入分类" :label-width="formLabelWidth">
          <el-input v-model="form.incomeCategory" autocomplete="off" />
        </el-form-item>
        <el-form-item label="收入金额" :label-width="formLabelWidth">
          <el-input v-model="form.amount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" />
        </el-form-item>
        <el-form-item label="交易时间" :label-width="formLabelWidth">
          <el-date-picker
              v-model="form.transactionTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="创建时间" v-show="showCreateTimeInput" :label-width="formLabelWidth">
          <el-input v-model="form.createTime" autocomplete="off" />
        </el-form-item>
        <el-form-item label="更新时间" v-show="showUpdateTimeInput" :label-width="formLabelWidth">
          <el-input v-model="form.updateTime" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  getIncomeRecordsPage,
  deleteIncomeRecords,
  saveOrUpdateIncomeRecords
} from '@/api/finance/financeApi.js'
import {ElMessage} from "element-plus";
import {
  getUserListByUserName
} from "@/api/userApi.js";
import {
  getFundAccountListByName
} from "@/api/finance/fundAccountApi.js";

const editBtnDisabled = ref(true)
const delBtnDisabled = ref(true)
const selectable = (row, index) => {
  return !!row;
}

const handleSelectionChange = (val) => {
  selectable.value = val

  if (val.length > 0) {
    editBtnDisabled.value = val.length !== 1;
    delBtnDisabled.value = false
  } else {
    editBtnDisabled.value = true
    delBtnDisabled.value = true
  }
}

const currentPage = ref(1)
const pageSize = ref(10)
const pageSizes = [10, 20, 30, 50]
const tableData = ref([])
const total = ref(0)

const fetchData = async () => {
  const query = {
    current: currentPage.value,
    size: pageSize.value
  }
  const response = await getIncomeRecordsPage(query)
  if (response.status && response.code === 200) {
    tableData.value = response.data.records
    total.value = response.data.total
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const dialogTitle = ref('')
const form = ref({
  id: '',
  username: '',
  fundAccountName: '',
  incomeCategory: '',
  amount: '',
  remark: '',
  transactionTime: '',
  createTime: '',
  updateTime: '',
})
const showIdInput = ref(false)
const showCreateTimeInput = ref(false)
const showUpdateTimeInput = ref(false)

const handleOpenDialog = (title, row) => {
  dialogTitle.value = title

  if (title === '新增收入记录') {
    form.value = {}
    form.value.transactionTime = new Date()
    showIdInput.value = false
    showCreateTimeInput.value = false
    showUpdateTimeInput.value = false
  } else {
    if (!row) {
      row = selectable.value[0]
    }
    Object.assign(form.value, row)
    showIdInput.value = true
    showCreateTimeInput.value = true
    showUpdateTimeInput.value = true
  }

  dialogFormVisible.value = true
}

const HandleDelete = async (row) => {
  const ids = row ? [row.id] : selectable.value.map(item => item.id)

  const response = await deleteIncomeRecords(ids)
  if (response.status && response.code === 200) {
    await fetchData()
  }
}

const handleSave = async () => {
  const response = await saveOrUpdateIncomeRecords(form.value)
  if (response.status && response.code === 200) {
    ElMessage.success('保存成功')
    dialogFormVisible.value = false
    await fetchData()
  }
}

const loading = ref(false)
const userOptions = ref([])

const userRemoteMethod = async (query) => {
  if (query) {
    loading.value = true;
    const response = await getUserListByUserName(query)
    if (response.status && response.code === 200) {
      userOptions.value = response.data
      loading.value = false;
    }
  } else {
    userOptions.value = [];
  }
}

const fundAccountOptions = ref([])

const fundAccountRemoteMethod = async (query) => {
  if (query) {
    loading.value = true;
    const response = await getFundAccountListByName(query)
    if (response.status && response.code === 200) {
      fundAccountOptions.value = response.data
      loading.value = false;
    }
  } else {
    fundAccountOptions.value = [];
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
@import '@/assets/less/general_table.less';
</style>